import re
from pathlib import Path
from core.backup import BackupManager
from plugins.template.adapter import PluginBase

class CentOSPlugin(PluginBase):
    def __init__(self):
        self.repo_dir = Path("/etc/yum.repos.d/")
        self.backup = BackupManager("centos")
    
    @classmethod
    def is_compatible(cls) -> bool:
        return Path("/etc/redhat-release").exists()
    
    def apply_mirror(self, mirror_url: str):
        """替换所有.repo文件的baseurl"""
        for repo_file in self.repo_dir.glob("*.repo"):
            self.backup.create(repo_file)
            content = repo_file.read_text()
            
            # 替换为清华镜像
            content = re.sub(
                r"^mirrorlist=.*$",
                "# mirrorlist=Removed by mirror-tool",
                content,
                flags=re.MULTILINE
            )
            content = re.sub(
                r"^#?\s*baseurl=.*$",
                f"baseurl={mirror_url}/centos/$releasever/",
                content,
                flags=re.MULTILINE
            )
            repo_file.write_text(content)